package com.castle.fortress.admin.contract.info.rest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.contract.info.entity.ContractEntity;
import com.castle.fortress.admin.contract.info.dto.ContractDto;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.contract.info.service.ContractService;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 合同信息表 api 控制器
 *
 * @author
 * @since 2025-04-23
 */
@Api(tags="合同信息表api管理控制器")
@RestController
@RequestMapping("/api/contract/info/contract")
public class ApiContractController {
    @Autowired
    private ContractService contractService;


    /**
     * 合同信息表的分页展示
     * @param contractDto 合同信息表实体类
     * @param currentPage 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation="合同信息表-api",operType = OperationTypeEnum.QUERY)
    @ApiOperation("合同信息表分页展示")
    @GetMapping("/page")
    public RespBody<IPage<ContractDto>> pageContract(ContractDto contractDto, @RequestParam(required = false) Integer currentPage, @RequestParam(required = false)Integer size){
        Integer pageIndex= currentPage==null? GlobalConstants.DEFAULT_PAGE_INDEX:currentPage;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<ContractDto> page = new Page(pageIndex, pageSize);

        // 使用自定义SQL查询
        IPage<ContractDto> pages = contractService.pageContractWithSql(page, contractDto);
        return RespBody.data(pages);
    }

    /**
     * 合同信息表保存
     * @param contractDto 合同信息表实体类
     * @return
     */
    @CastleLog(operLocation="合同信息表-api",operType = OperationTypeEnum.INSERT)
    @ApiOperation("合同信息表保存")
    @PostMapping("/save")
    public RespBody<String> saveContract(@RequestBody ContractDto contractDto){
        if(contractDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
            ContractEntity contractEntity = ConvertUtil.transformObj(contractDto,ContractEntity.class);
        if(contractService.save(contractEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 合同信息表编辑
     * @param contractDto 合同信息表实体类
     * @return
     */
    @CastleLog(operLocation="合同信息表-api",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("合同信息表编辑")
    @PostMapping("/edit")
    public RespBody<String> updateContract(@RequestBody ContractDto contractDto){
        if(contractDto == null || contractDto.getContractId() == null || contractDto.getContractId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
            ContractEntity contractEntity = ConvertUtil.transformObj(contractDto,ContractEntity.class);
        if(contractService.updateById(contractEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 合同信息表删除
     * @param ids 合同信息表id集合
     * @return
     */
    @CastleLog(operLocation="合同信息表-api",operType = OperationTypeEnum.DELETE)
    @ApiOperation("合同信息表删除")
    @PostMapping("/delete")
    public RespBody<String> deleteContract(@RequestBody List<Long> ids){
        if(ids == null || ids.isEmpty()){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(contractService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 合同信息表详情
     * @param id 合同信息表id
     * @return
     */
    @CastleLog(operLocation="合同信息表-api",operType = OperationTypeEnum.QUERY)
    @ApiOperation("合同信息表详情")
    @GetMapping("/info")
    public RespBody<ContractDto> infoContract(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
            ContractEntity contractEntity = contractService.getById(id);
            ContractDto contractDto = ConvertUtil.transformObj(contractEntity,ContractDto.class);
        return RespBody.data(contractDto);
    }

    /**
     * 级联删除合同及相关数据
     * 删除合同表数据的同时，级联删除与之关联的审核记录和规则关联数据
     * 
     * @param ids 合同ID列表
     * @return 操作结果
     */
    @CastleLog(operLocation="合同信息表-api",operType = OperationTypeEnum.DELETE)
    @ApiOperation("级联删除合同及相关数据")
    @PostMapping("/cascadeDelete")
    public RespBody<String> cascadeDeleteContract(@RequestBody List<Long> ids) {
        try {
            // 验证参数
            if(ids == null || ids.isEmpty()) {
                throw new BizException(GlobalRespCode.PARAM_MISSED);
            }
            
            // 批量级联删除
            boolean allSuccess = true;
            StringBuilder failedIds = new StringBuilder();
            
            for (Long contractId : ids) {
                boolean success = contractService.cascadeDeleteContract(contractId);
                if (!success) {
                    allSuccess = false;
                    failedIds.append(contractId).append(",");
                }
            }
            
            if(allSuccess) {
                return RespBody.data("级联删除成功");
            } else {
                return RespBody.fail("部分删除失败，请检查以下ID：" + 
                        (failedIds.length() > 0 ? failedIds.substring(0, failedIds.length() - 1) : ""));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RespBody.fail("系统异常: " + e.getMessage());
        }
    }
}
